package com.zk.babala.datasource;

import com.zk.babala.entity.CategoryInfo;
import com.zk.babala.entity.LineInfo;
import com.zk.babala.entity.Movie;
import com.zk.babala.entity.PlayNumInfo;
import com.zk.babala.entity.VideoInfo;
import com.zk.babala.service.ISourceParse;
import com.zk.babala.util.LineUtil;
import com.zk.babala.util.RequestUtil;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: zhangke
 * @Date: 2022/4/11 17:20
 */
public class YingHuaSource implements ISourceParse {
    private String nextUrl;
    private String searchUrl;
    public static String defaultUrl = "https://www.yinghua12.com/";

    @Override
    public Map<String, String> getSourceMeta() {
        Map<String, String> map = new HashMap<>();
        map.put("source", this.getClass().getSimpleName());
        map.put("name", "樱花视频");
        map.put("url", defaultUrl);
        return map;
    }


    @Override
    public List<CategoryInfo> getCategory() {
        List<CategoryInfo> categoryInfoList = new ArrayList<>();
        categoryInfoList.add(new CategoryInfo("热播", ""));
        categoryInfoList.add(new CategoryInfo("国产动漫", "index.php/vod/type/id/21.html"));
        categoryInfoList.add(new CategoryInfo("日本动漫", "index.php/vod/type/id/20.html"));
        categoryInfoList.add(new CategoryInfo("动漫电影", "index.php/vod/type/id/23.html"));
        categoryInfoList.add(new CategoryInfo("欧美动漫", "index.php/vod/type/id/22.html"));
        categoryInfoList.add(new CategoryInfo("其他动漫", "index.php/vod/type/id/24.html"));
        searchUrl = "index.php/vod/search.html?wd=";
        return categoryInfoList;
    }


    @Override
    public List<Movie> getMovies(String url) {
        List<Movie> list = new ArrayList<>();
        Document document = RequestUtil.get(url);
        document.getElementsByClass("stui-vodlist__thumb").forEach(a -> {
            if (!a.attr("title").isEmpty()) {
                Movie m = new Movie();
                m.setTitle(a.attr("title"));
                m.setVideoUrl(LineUtil.getLineUtil().swapUrl(a.attr("href")));

                // 获取 data-original 属性的图片URL
                String cardImageUrl = a.attr("data-original");
                // 如果 data-original 为空，尝试从 style 属性中提取 background-image URL
                if (cardImageUrl == null || cardImageUrl.isEmpty()) {
                    String style = a.attr("style");
                    if (style != null && !style.isEmpty()) {
                        cardImageUrl = extractBackgroundImageUrl(style);
                    }
                }

                m.setCardImageUrl(LineUtil.getLineUtil().swapUrl(cardImageUrl));
                list.add(m);
            }

        });
        nextUrl = null;
        Elements pageElement = document.getElementsByClass("stui-page");
        if (!pageElement.isEmpty()) {
            pageElement.get(0).getElementsByTag("a").forEach(page -> {
                if (page.text().equals("下一页")) {
                    nextUrl = page.attr("href");
                }
            });
        }
        return list;
    }

    @Override
    public VideoInfo getVideoDetail(String url) {
        VideoInfo videoInfo = new VideoInfo();
        Document document = RequestUtil.get(url);
        Elements infoNodes = document.getElementsByClass("stui-content__detail").get(0).getElementsByTag("p");
        infoNodes.forEach(infoNode -> {
            videoInfo.getDetailInfoList().add(infoNode.text());
        });
        List<LineInfo> lineInfoList = new ArrayList<>();
        Elements playNodes = document.getElementsByClass("stui-pannel-box b playlist mb");
        if (playNodes.isEmpty()) {
            playNodes = document.getElementsByClass("tab-pane fade in clearfix");
        }
        for (int i = 0; i < playNodes.size(); i++) {
            Element node = playNodes.get(i);
            List<PlayNumInfo> playItemList = new ArrayList<>();
            Elements playList = node.getElementsByTag("a");
            for (int p = 0; p < playList.size(); p++) {
                Element item = playList.get(p);
                PlayNumInfo play = new PlayNumInfo();
                play.setId(p);
                play.setTitle(item.text());
                play.setPageUrl(item.attr("href"));
                playItemList.add(play);
            }

            String lineTitle = node.getElementsByTag("h3").isEmpty() ? null : node.getElementsByTag("h3").text();
            if (lineTitle == null) {
                Elements line = document.getElementsByAttributeValue("href", "#" + node.attr("id"));
                if (!line.isEmpty()) {
                    lineTitle = line.text();
                } else {
                    lineTitle = "线路" + i;
                }

            }
            LineInfo lineInfo = new LineInfo();
            lineInfo.setTitle(lineTitle);
            lineInfo.setPlayNumInfoList(playItemList);
            lineInfoList.add(lineInfo);
        }

        videoInfo.setLineInfoList(lineInfoList);
        return videoInfo;
    }

    @Override
    public String getPlayUrl(String url) {
        Document document = RequestUtil.get(url);
        String content = document.getElementsByClass("stui-player__video").get(0).toString();
        return LineUtil.getLineUtil().getPlayUrl(content);
    }

    @Override
    public String getSearchUrl() {
        return LineUtil.getLineUtil().getLine() + searchUrl;
    }


    @Override
    public List<Movie> search(String word) {
        String searchUrl = getSearchUrl() + word;
        nextUrl = null;
        return getMovies(searchUrl);
    }

    @Override
    public List<Movie> loadNext() {
        if (nextUrl == null) {
            return Collections.emptyList();
        } else {
            return getMovies(nextUrl);
        }
    }

    /**
     * 从 style 属性中提取 background-image 的 URL
     *
     * @param style style 属性字符串
     * @return 提取到的图片URL，如果未找到则返回空字符串
     */
    private String extractBackgroundImageUrl(String style) {
        Pattern pattern = Pattern.compile("background(?:-image)?\\s*:\\s*url\\(['\"]?(.*?)['\"]?\\)");
        Matcher matcher = pattern.matcher(style);
        if (matcher.find()) {
            return matcher.group(1);
        }

        return "";
    }
}
